<?php
namespace app\admin\controller;
use app\common\model\Orders;
use app\common\model\OrdersItem;
use think\Validate;
use think\Db;
use think\Session;

class PurchaseController extends BaseController
{
    public function lists()
    {
        return view();
    }
    public function getList()
    {
        $where = array_filter(input('post.'));

        if (!empty($where['cate_name'])) {
            $where['g.cate_id'] = Db::name('goods_categories')->where('name',$where['cate_name'])->value('id');
            unset($where['cate_name']);
            // $where['status'] = ['in',[1,3]];
        }
        if (!empty($where['brand_name'])) {
            $where['g.brand_id'] = Db::name('goods_brand')->where('name',$where['brand_name'])->value('id');
            unset($where['brand_name']);
            // $where['status'] = ['in',[1,3]];
        }
        if (!empty($where['stall_name'])) {
            $where['stall_id'] = Db::name('stall')->where('name',$where['stall_name'])->value('id');
            unset($where['stall_name']);
            // $where['status'] = ['in',[1,3]];
        }
        if (!empty($where['acct_name'])) {
            $where['c_saler_id'] = Db::name('account')->where('true_name',$where['acct_name'])->value('id');
            unset($where['acct_name']);
            // $where['status'] = ['in',[1,3]];
        }
        if (!empty($where['order_sn'])) {
            // $where['oi.order_sn'] = $where['order_sn'];
            unset($where['order_sn']);
            // $where['status'] = ['in',[1,3]];
        }
        // 订单号搜索
        if (!empty($where['order_no'])) {
            $order_id = Orders::where('order_no',$where['order_no'])->value('id');
            // dump($order_id );
            $order_item_ids = OrdersItem::where('order_id',$order_id)->column('id');
            // dump($order_item_ids );
            $where['order_item_id'] = ['in',$order_item_ids];
            unset($where['order_no']);
            // $where['status'] = ['in',[1,3]];
        }

        $page = max(input('get.page',0),1);
        $page_size = 15;
        // 获取团队 
        $account_id = Session::get('uid');
        $account_member = Db::name('account_member')->where('account_id',$account_id)->select();
        if(!empty($account_member)){
            $organization_list = array_map(function($item){
                return $item['organization_id'];
            },collection($account_member)->toArray());
            $where['organization_id'] = ['in',$organization_list];
        }
        $total = Db::name('purchase')->alias('p')
                                    ->join('__GOODS__ g','c_goods_id = g.id')
                                    ->join('__ORDERS_ITEM__ oi', 'oi.id = p.order_item_id')
                                    ->join('__ORDERS__ o', 'o.id = oi.order_id')
                                    ->where($where)->count();

        $rows = Db::name('purchase')->alias('p')
                                    ->join('__GOODS__ g','c_goods_id = g.id')
                                    ->join('__ORDERS_ITEM__ oi', 'oi.id = p.order_item_id')
                                    ->join('__ORDERS__ o', 'o.id = oi.order_id')
                                    ->where($where)
                                    ->field('p.*,g.name as goods_name,picture as goods_pic')
                                    ->order('p.add_time desc')
                                    ->page($page, $page_size)
                                    ->select();
        $this->addon($rows);        

        $data = [
            'rows'      => $rows,
            'total_page'=> ceil($total/$page_size),
            'page_size' => $page_size,
            'page'      => $page
        ];
        $this->success('获取成功','',$data);
    }
    protected function addon(&$rows)
    {
        //账号信息
        $acct_ids1 = array_column($rows, 'acct_id');
        $acct_ids2 = array_column($rows, 'c_saler_id');
        $acct_ids = array_unique( array_merge($acct_ids1, $acct_ids2) );
        $acct_map = Db::name('account')->where('id', 'in', $acct_ids)->column('');

        //档口信息
        $stall_map = Db::name('stall')->where('id', 'in', array_column($rows, 'stall_id'))->column('');

        //订单信息
        $oi_map = Db::name('orders_item')
                            ->alias('oi')
                            ->join('__ORDERS__ o', 'o.id = oi.order_id')
                            ->where('oi.id', 'in', array_column($rows,'order_item_id'))
                            ->column('oi.id,order_no,order_sn,goods_id,color,spec,qty,acct_id','oi.id');

        $status_txt = [
            1   => '等待到货',
            2   => '已取消',
            3   => '已到货'
        ];
        $stock_in_model = Db::name('stock_in');
        foreach ($rows as &$row) {

            $row['status_txt'] = $status_txt[$row['status']];
            $row['add_day'] = date('Y-m-d', $row['add_time']);
            $row['add_time'] = date('H:i', $row['add_time']);
            $row['goods_pic'] = config('upload_path') . $row['goods_pic'];
            $row['pic_tmb'] = $this->getThumb($row['goods_pic']);
            $row['stock'] = $stock_in_model->where('purchase_id', $row['id'])->sum('qty');

            $row['acct_name'] = $acct_map[$row['acct_id']]['true_name'];
            
            $oi = $oi_map[$row['order_item_id']];
            $row['order_no'] = $oi['order_no'];
            $row['order_sn'] = $oi['order_sn'];
            $row['color'] = $oi['color'];
            $row['spec'] = $oi['spec'];
            $row['o_qty'] = $oi['qty'];

            $row['saler'] = $acct_map[$row['c_saler_id']]['true_name'];
            $row['stall_name'] = $stall_map[$row['stall_id']]['name'];
            
            //验证
            $row['err'] = '';
            if ($oi['goods_id'] != $row['c_goods_id']) {
                $row['err'] .= 'A';
            };
            if ($oi['acct_id'] != $row['c_saler_id']) {
                $row['err'] .= 'B';
            };
        }
    }
    public function orderItemList()
    {
        return view();
    }
    public function handle()
    {
        $data = input('post.');
        //return $data;
        $validate = new Validate([
            ['order_item_id','require','error1'],
            ['stall_name','require','档口必需'],
            ['price','require|number','单价必需|单价必须是数值'],
        ]);
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        //检查档口
        $stall = Db::name('stall')->where(['name'=>$data['stall_name'],'parent_id'=>['>',0]])->find();
        if (empty($stall)) {
            $this->error('档口不存在');
        }
        //判断重复
        $row = Db::name('purchase')->where(['order_item_id'=>$data['order_item_id'],'status'=>1])->find();
        if ($row) {
            $this->error('此订单已报单');
        }
        
        $oi_info = Db::name('orders_item')->where('id',$data['order_item_id'])->find();
        $info = [
            'order_item_id' => $data['order_item_id'],
            'stall_id'      => $stall['id'],
            'price'         => $data['price'],
            'factory_price' => $data['factory_price'],
            'remarks'       => $data['remarks'],
            'acct_id'       => Session::get('uid'),
            'add_time'      => time(),
            'c_goods_id'    => $oi_info['goods_id'],
            'c_saler_id'    => Db::name('orders')->where('id',$oi_info['order_id'])->value('acct_id')
        ];
        // 判断订单是否团队订单
        $orders = Db::name('orders')->where(['order_no'=>$data['order_no']])->find();
        if(!empty($orders['organization_id'])){
            $info['organization_id'] = $orders['organization_id'];
        }
        if( Db::name('purchase')->insert($info) ){
            //更新订单状态
            $oi_model = new OrdersItem();
            $oi_model->updateProgress($info['order_item_id']);
            $this->success('操作成功');
        } else {
            $this->error('操作失败');
        }
    }
    public function editHandle()
    {
        $data = input('post.');
        //return $data;
        $validate = new Validate([
            ['id','require','error1'],
            ['stall_name','require','档口必需'],
            ['price','require|number','单价必需|单价必须是数值'],
        ]);
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        
        //检查档口
        $stall = Db::name('stall')->where(['name'=>$data['stall_name'],'parent_id'=>['>',0]])->find();
        if (empty($stall)) {
            $this->error('档口不存在');
        }
        $purchase_info = Db::name('purchase')->where('id',$data['id'])->find();
        // if (time() - $purchase_info['add_time'] > 10*24*60*60) {
        //     $this->error('超过10天不能修改');
        // }
        
        $info = [
            'stall_id'      => $stall['id'],
            'price'         => $data['price'],
            'factory_price'       => $data['factory_price']
        ];
        
        if( Db::name('purchase')->where('id',$data['id'])->update($info) ){
            $this->success('操作成功');
        } else {
            $this->error('操作失败');
        }
    }
    public function cancel()
    {
        $id = input('id');
        // return $id;
        //到货不能取消
        $status = Db::name('purchase')->where('id', $id)->value('status');
        if ($status == 3) {
            $this->error('已到货不能取消');
        }
        if( Db::name('purchase')->where('id', $id)->update(['status'=>2]) ) {
            //更新订单状态(新订单)
            $order_item_id = Db::name('purchase')->where('id', $id)->value('order_item_id');
            Db::name('orders_item')->where('id', $order_item_id)->update(['progress' => 1]);
            $this->success('取消成功');
        } else {
            $this->error('取消失败');
        }

    }
    /**
     * 删除到货登记
     */
    public function del()
    {
        $id = $this->request->param('id');
        // return $id;
        //到货不能取消
        $status = Db::name('purchase')->where('id', $id)->value('status');
        if ($status == 3) {
            $this->error('已到货不能取消');
        }
        if( Db::name('purchase')->where('id', $id)->delete() ) {
            //更新订单状态(新订单)
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }

    }
}